﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using S.Common.helper;
using S.Parturition.API.Application.Command;
using S.Parturition.API.Dto;
using S.Parturition.Domain;
using S.Parturition.Domain.Model;
using S.Parturition.Infrastructure.Interface;

namespace S.Parturition.API.Application.CommandHandlers
{
    public class AddLambRegistrationHandler : IRequestHandler<AddLambRegistrationCommand, bool>
    {

        private readonly ILambRegistrationRepository repository;

        private readonly IMapper mapper;

        private readonly MyDbContext dbContext;
        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public AddLambRegistrationHandler(ILambRegistrationRepository repository, IMapper mapper, MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.dbContext = dbContext;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }

        public async Task<bool> Handle(AddLambRegistrationCommand request, CancellationToken cancellationToken)
        {

            //使用事物
            using (var tran = dbContext.Database.BeginTransaction())
            {
                try
                {
                    string Gateway = configuration.GetValue<string>("Gateway");

                    #region 添加羔羊登记信息
                    //使用automapper进行传值
                    LambRegistrationModel lamb = mapper.Map<LambRegistrationModel>(request);
                    lamb.CreateDate = DateTime.Now;
                    lamb.SheepStatus = false;
                    await repository.AddAsync(lamb);

                    #endregion

                    #region 添加后裔档案信息

                    //后裔档案信息
                    SheepFileCreateDto sheep = new SheepFileCreateDto()
                    {
                        EarTag = lamb.EarTag,
                        ParentEarTag = lamb.FatherEar,
                        MotherEarTag = lamb.MotherEar,
                        Variety = lamb.LambBreed,
                        Sex = lamb.Sex == true ? 1 : 2,
                        BirthDate = lamb.BirthDate,
                        BirthState = 4,
                        AdmissionDate = lamb.BirthDate,
                        BirthPlace = "本厂",
                        BirthWeight = lamb.BirthWeight,
                        GeneRank = 4,
                        Remarks = "",
                        ReproductiveState = 0,
                        PresenceState = 2,
                        IsPassAway = false,
                        IsElimination = false,
                        FileType = 3,
                        CreateBy = "",
                        CreateDate = DateTime.Now,
                        UpdateBy = "",
                        UpdateDate = null,
                    };
                    //跨服务调用添加转舍接口
                    var archives = HttpClientHelper.PostResponse($"{Gateway}/achs/api/SheepFileModel/AddSheepFile", sheep);
                    if (archives == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion

                    #region 反填并修改种母历史记录

                    var editBreed = new EditBreed
                    {
                        EarTag = lamb.MotherEar,
                    };

                    //反填种母历史记录
                    var jsonString = HttpClientHelper.PostResponseKey($"{Gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
                    //将获取到的种母历史记录序列化
                    var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                    if (string.IsNullOrWhiteSpace(jsonString))
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    //修改分娩的羔羊数量
                    switch (lamb.BirthState)//根据羔羊出生状态判断
                    {
                        case 1:
                            response.HealthyNumber++;
                            response.TotalWeightOfHealthyLambs += lamb.BirthWeight;
                            break;
                        case 2:
                            response.LambNumber++;
                            break;
                        case 3:
                            response.DeformityNumber++;
                            break;
                        case 4:
                            response.StillbirthsNumber++;
                            break;
                        case 5:
                            response.MummyNumber++;
                            break;
                        case 6:
                            response.FreaksNumber++;
                            break;
                    }

                    response.IsEditor = true;

                    //修改种母历史记录
                    var breeding = HttpClientHelper.PutDataResponse($"{Gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                    if (breeding == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion                    

                    #region 添加转舍信息

                    //获取到种母信息
                    var mother = HttpClientHelper.GetResponse<ParturitionModel>($"{Gateway}/ParturitionRead/api/Parturition/GetLambParturition?EarTag=" + lamb.MotherEar);

                    TransferDto transferDto = new TransferDto()
                    {
                        EarTag = lamb.EarTag,
                        SurrenderDate = lamb.BirthDate,
                        RoundType = 11,
                        ShiftToBuild = Convert.ToInt32(mother.ShiftToBuild),
                        ShiftToHuts = Convert.ToInt32(mother.ShiftToHuts),
                        ShiftToBuildingManagementId = Convert.ToInt32(mother.ShiftToBuild),
                        ShiftToColumnManagementId = Convert.ToInt32(mother.ShiftToHuts),
                        DocumentNumbe = Convert.ToInt64(mother.DocumentNumber),
                        Type = lamb.EarTag,
                    };
                    //跨服务调用添加转舍接口
                    var transfer = HttpClientHelper.PostResponse($"{Gateway}/transset/api/TransFer/CreateSheepTransFer", transferDto);

                    if (transfer == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion


                    //事物执行
                    tran.Commit();

                    return true;
                }
                catch (Exception)
                {
                    //事物回滚
                    tran.Rollback();

                    return false;
                }
            }
        }

        public class EditBreed
        {
            public string EarTag { get; set; }
        }
    }
}
